/*      
 * File:   config.cpp
 * Author: Faraj
 * 
 * Created on May 5, 2013, 4:24 PM
 */
#include "config.h"

lib::config::config(string filename) {
    this->_filename = filename;
    this->_fetch();
}

bool lib::config::is_loaded(){
    return this->_loaded;
}

lib::config::~config() {
    _params.clear();
}

string lib::config::lookup(string key) {
    return _params[key];
}

vector<string> lib::config::keys(string key){   
    //common::log::trace("config.keys " + key);
    vector<string> keys;
    for(map<string,string>::iterator it = _params.begin(); it != _params.end(); ++it) {
        string ikey = it->first;  
        //common::log::trace("config.keys.ikey " + ikey);
        if(common::str::startswith(key, ikey)){
            //common::log::trace("config.keys.ikey.compared " + ikey);            
            ikey = common::str::replace(ikey, key + ".", "");
            size_t pos = ikey.find(".");
            if(pos != string::npos){
                ikey.replace(pos,ikey.size(),"");
            }
            //common::log::trace("config.keys.ikey.altered " + ikey);            
            bool found = false;
            for(vector<string>::iterator itkeys = keys.begin(); itkeys != keys.end(); ++itkeys){
                found |= (0 == ikey.compare(*itkeys));
            }
            if(!found){
                keys.push_back(ikey);
            }
        }
    }    
    return keys;
}

void lib::config::_fetch() {
    string line;
    ifstream file(this->_filename.c_str());
    _loaded = file.is_open();
    if (_loaded) {
        while (!file.eof()) {
            getline(file, line);
            if(line[0] != '#' && common::str::contains("=", line)){
                vector<string> arr = common::str::explode("=", line);
                _params[arr[0]] = arr[1];
            }
        }
        file.close();
    }
}

void lib::config::load() {
    this->_fetch();
}